<?php

namespace app\store\controller\apps\dealer;

use app\store\controller\Controller;
use app\store\model\dealer\Withdraw as WithdrawModel;
use app\store\model\dealer\User as UserModel;
use app\store\model\dealer\Setting as SettingModel;
use app\store\service\order\Export as Exportservice;
use think\Db;
use app\store\model\Categoryy as CategoryModel;

/**
 * 分销商提现申请
 * Class Setting
 * @package app\store\controller\apps\dealer
 */
class Withdraw extends Controller
{
    public function tree()
    {
        $wxapp_id   = 10001;
        $keyword    = input('get.keyword', '', 'trim');
        $start_time = input('get.start_time', '', 'trim');
        $end_time   = input('get.end_time', '', 'trim');

        // 是否纯数字（用于更友好的手机号/ID精确命中）
        $isNumeric = ($keyword !== '' && ctype_digit($keyword));

        // 1) 获取一级分销用户
        $dealerQuery = Db::name('dealer_user')
            ->alias('du')
            ->join('user u', 'u.user_id = du.user_id', 'LEFT')
            ->join('user_jiuzhen uj', 'uj.user_id = du.user_id', 'LEFT')
            ->where('du.wxapp_id', $wxapp_id)
            ->where('du.is_delete', 0);

        if ($keyword !== '') {
            $dealerQuery->where(function ($q) use ($keyword, $isNumeric) {
                // 用户ID / 手机（分销表mobile + 就诊表phone）/ 昵称 / 姓名
                if ($isNumeric) {
                    $q->whereOr('du.user_id', $keyword)
                    ->whereOr('du.mobile', 'like', "%{$keyword}%")
                    ->whereOr('uj.phone', 'like', "%{$keyword}%");
                } else {
                    $q->whereOr('du.mobile', 'like', "%{$keyword}%")
                    ->whereOr('uj.phone', 'like', "%{$keyword}%");
                }
                $q->whereOr('u.nickname', 'like', "%{$keyword}%")
                ->whereOr('uj.name',     'like', "%{$keyword}%");
            });
        }

        // 时间范围（创建时间在 dealer_user）
        if ($start_time !== '' && $end_time !== '') {
            $start = strtotime($start_time);
            $end   = strtotime($end_time . ' 23:59:59');
            if ($start > $end) { [$start, $end] = [$end, $start]; }
            $dealerQuery->whereBetween('du.create_time', [$start, $end]);
        } elseif ($start_time !== '') {
            $dealerQuery->where('du.create_time', '>=', strtotime($start_time));
        } elseif ($end_time !== '') {
            $dealerQuery->where('du.create_time', '<=', strtotime($end_time . ' 23:59:59'));
        }

        // 把手机号一并查出：uj.phone AS phone
        $dealerList = $dealerQuery
            ->field('du.user_id as category_id, 0 as parent_id, du.create_time, uj.name, uj.phone')
            ->select()
            ->toArray();

        foreach ($dealerList as &$item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            $item['child'] = [];
            // 兜底
            $item['name']  = $item['name']  ?? '';
            $item['phone'] = $item['phone'] ?? '';
        }
        unset($item);

        if (empty($dealerList)) {
            return $this->fetch('tree', ['tree' => []]);
        }

        $rootUserIds = array_column($dealerList, 'category_id');

        // 2) 获取所有后代（无限级，包含就诊人手机号）
        $relations = $this->getAllDescendants($rootUserIds, $wxapp_id);

        // 3) 合并
        $items = [];
        foreach ($dealerList as $it) {
            $items[$it['category_id']] = $it; // 根优先
        }
        foreach ($relations as $it) {
            if (!isset($items[$it['category_id']])) {
                $items[$it['category_id']] = $it;
            } else {
                // 若子节点也在根集合，补 parent_id 不覆盖根的信息
                $items[$it['category_id']]['parent_id'] = $it['parent_id'];
                // 若根没有手机号/姓名，用子节点查出的补齐
                if (empty($items[$it['category_id']]['phone']) && !empty($it['phone'])) {
                    $items[$it['category_id']]['phone'] = $it['phone'];
                }
                if (empty($items[$it['category_id']]['name']) && !empty($it['name'])) {
                    $items[$it['category_id']]['name'] = $it['name'];
                }
            }
        }

        // 4) 建树
        $tree = [];
        foreach ($items as $id => &$it) {
            if (isset($items[$it['parent_id']])) {
                $items[$it['parent_id']]['child'][] = &$items[$id];
            } else {
                $tree[$id] = &$items[$id];
            }
        }
        unset($it);

        return $this->fetch('tree', compact('tree'));
    }

    /**
     * 递归/迭代获取所有后代（含就诊人手机号）
     */
    private function getAllDescendants($rootUserIds, $wxapp_id)
    {
        $all   = [];
        $queue = array_values(array_unique($rootUserIds));
        $seen  = []; // descendant_user_id 去重

        while (!empty($queue)) {
            $children = Db::name('dealer_relation_tree')
                ->alias('tree')
                ->join('user_jiuzhen uj', 'uj.user_id = tree.descendant_user_id', 'LEFT')
                ->where('tree.wxapp_id', $wxapp_id)
                ->whereIn('tree.ancestor_user_id', $queue)
                // 同样把手机号查出来
                ->field('tree.descendant_user_id as category_id, tree.ancestor_user_id as parent_id, tree.create_time, uj.name, uj.phone')
                ->select()
                ->toArray();

            $next = [];
            foreach ($children as $row) {
                if (isset($seen[$row['category_id']])) continue;
                $seen[$row['category_id']] = true;

                $row['create_time'] = date('Y-m-d H:i:s', $row['create_time']);
                $row['child'] = [];
                $row['name']  = $row['name']  ?? '';
                $row['phone'] = $row['phone'] ?? '';

                $all[]  = $row;
                $next[] = $row['category_id'];
            }
            $queue = $next;
        }
        return $all;
    }
    
    // 构建树的递归函数
    private function buildTree($ancestorId, $relations, $users, $jiuzhen)
    {
        $node = [
            'user_id' => $ancestorId,
            'label' => $users[$ancestorId]['nickName'] ?? '未知昵称',
            'mobile' => $jiuzhen[$ancestorId]['phone'] ?? '',
            'real_name' => $jiuzhen[$ancestorId]['name'] ?? '',
            'children' => [],
        ];
    
        foreach ($relations as $rel) {
            if ((int)$rel['ancestor_user_id'] === (int)$ancestorId && (int)$rel['depth'] === 1) {
                $node['children'][] = $this->buildTree($rel['descendant_user_id'], $relations, $users, $jiuzhen);
            }
        }
    
        return $node;
    }
    /**
     * 分销商导出
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function export1($search = '',$start_time = '' ,$end_time = '', $sort_order = 'desc')
    {
        $model = new UserModel;
        $data = $model->getList1($search,$start_time ,$end_time,$sortOrder = 'desc',$pagesite = 111111111111111);
        // 设置表头
        $headers = ['分销员','推荐人', '手机号', '下级数量', '注册时间'];
        return (new Exportservice)->delist2($headers,$data);
    }
    /**
     * 分销排名
     * @param int $user_id
     * @param int $apply_status
     * @param int $pay_type
     * @param string $search
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index($user_id = null, $start_time = '', $end_time = '', $search = '', $sort_order = 'desc')
    {
        $model = new UserModel;
        // dump($model->getList1($search,$start_time ,$end_time));die;
        return $this->fetch('index', [
            'list' => $model->getList1($search,$start_time ,$end_time,$sort_order),
            'basicSetting' => SettingModel::getItem('basic'),
        ]);
        // echo 1;die;
        // $model = new WithdrawModel;
        // return $this->fetch('index', [
        //     'list' => $model->getList1($user_id, $start_time, $end_time, $search)
        // ]);
    }

    /**
     * 提现审核
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public function submit($id)
    {
        $model = WithdrawModel::detail($id);
        if ($model->submit($this->postData('withdraw'))) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 确认打款
     * @param $id
     * @return array
     * @throws \think\exception\DbException
     */
    public function money($id)
    {
        // 提现记录详情
        $model = WithdrawModel::detail($id);
        if ($model->money()) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }

    /**
     * 分销商提现：微信支付企业付款
     * @param $id
     * @return array|bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function wechat_pay($id)
    {
        $model = WithdrawModel::detail($id);
        // 验证已冻结佣金是否合法
        if (!$model->verifyUserFreezeMoney($model['user_id'], $model['money'])) {
            return $this->renderError($model->getError());
        }
        // 合法 -> 确认打款
        if ($model->wechatPay()) {
            return $this->renderSuccess('操作成功');
        }
        return $this->renderError($model->getError() ?: '操作失败');
    }
    /**
     * 导出当前筛选结果（CSV）
     * 路由示例：/store/apps.dealer.withdraw/export
     */
    public function export()
    {
        $wxapp_id   = 10001;
        $keyword    = input('get.keyword', '', 'trim');
        $start_time = input('get.start_time', '', 'trim');
        $end_time   = input('get.end_time',   '', 'trim');

        $isNumeric = ($keyword !== '' && ctype_digit($keyword));

        // 1) 取一级 (dealer_user) —— 和 tree() 保持一致
        $dealerQuery = Db::name('dealer_user')
            ->alias('du')
            ->join('user u', 'u.user_id = du.user_id', 'LEFT')
            ->join('user_jiuzhen uj', 'uj.user_id = du.user_id', 'LEFT')
            ->where('du.wxapp_id', $wxapp_id)
            ->where('du.is_delete', 0);

        if ($keyword !== '') {
            $dealerQuery->where(function ($q) use ($keyword, $isNumeric) {
                if ($isNumeric) {
                    $q->whereOr('du.user_id', $keyword)
                    ->whereOr('du.mobile', 'like', "%{$keyword}%")
                    ->whereOr('uj.phone', 'like', "%{$keyword}%");
                } else {
                    $q->whereOr('du.mobile', 'like', "%{$keyword}%")
                    ->whereOr('uj.phone', 'like', "%{$keyword}%");
                }
                $q->whereOr('u.nickname', 'like', "%{$keyword}%")
                ->whereOr('uj.name',     'like', "%{$keyword}%");
            });
        }

        if ($start_time !== '' && $end_time !== '') {
            $start = strtotime($start_time);
            $end   = strtotime($end_time . ' 23:59:59');
            if ($start > $end) { [$start, $end] = [$end, $start]; }
            $dealerQuery->whereBetween('du.create_time', [$start, $end]);
        } elseif ($start_time !== '') {
            $dealerQuery->where('du.create_time', '>=', strtotime($start_time));
        } elseif ($end_time !== '') {
            $dealerQuery->where('du.create_time', '<=', strtotime($end_time . ' 23:59:59'));
        }

        $dealerList = $dealerQuery
            ->field('du.user_id as category_id, 0 as parent_id, du.create_time, uj.name, uj.phone')
            ->select()
            ->toArray();

        foreach ($dealerList as &$it) {
            $it['create_time'] = date('Y-m-d H:i:s', $it['create_time']);
            $it['child'] = [];
            $it['name']  = $it['name']  ?? '';
            $it['phone'] = $it['phone'] ?? '';
        }
        unset($it);

        if (empty($dealerList)) {
            // 没有数据也导出一个空表头
            $this->outputCsv('tree_export.csv', [
                ['用户ID','用户名','电话','级别','父级ID','时间']
            ]);
            return;
        }

        $rootUserIds = array_column($dealerList, 'category_id');

        // 2) 全部后代（与 tree() 同步）
        $relations = $this->getAllDescendants($rootUserIds, $wxapp_id);

        // 3) 合并 map
        $items = [];
        foreach ($dealerList as $it) {
            $items[$it['category_id']] = $it;
        }
        foreach ($relations as $it) {
            if (!isset($items[$it['category_id']])) {
                $items[$it['category_id']] = $it;
            } else {
                $items[$it['category_id']]['parent_id'] = $it['parent_id'];
                if (empty($items[$it['category_id']]['phone']) && !empty($it['phone'])) {
                    $items[$it['category_id']]['phone'] = $it['phone'];
                }
                if (empty($items[$it['category_id']]['name']) && !empty($it['name'])) {
                    $items[$it['category_id']]['name'] = $it['name'];
                }
            }
        }

        // 4) 建树
        $tree = [];
        foreach ($items as $id => &$it) {
            if (isset($items[$it['parent_id']])) {
                $items[$it['parent_id']]['child'][] = &$items[$id];
            } else {
                $tree[$id] = &$items[$id];
            }
        }
        unset($it);

        // 5) 拍平（带级别）
        $rows = [];
        $this->flattenTree($tree, 1, 0, $rows);

        // 6) 导出
        $data = [['用户ID','用户名','电话','级别','父级ID','时间']];
        foreach ($rows as $r) {
            $data[] = [
                $r['category_id'],
                $r['name'] ?: '未知姓名',
                $r['phone'] ?: '',
                $r['level'],
                $r['parent_id'],
                $r['create_time'],
            ];
        }
        $this->outputCsv('tree_export_' . date('Ymd_His') . '.csv', $data);
    }

    /**
     * 拍平树
     * @param array $nodes
     * @param int   $level
     * @param int   $parentId
     * @param array $rows
     */
    private function flattenTree(array $nodes, int $level, int $parentId, array &$rows)
    {
        foreach ($nodes as $node) {
            $rows[] = [
                'category_id' => $node['category_id'],
                'name'        => $node['name'] ?? '',
                'phone'       => $node['phone'] ?? '',
                'level'       => $level,
                'parent_id'   => $parentId,
                'create_time' => $node['create_time'],
            ];
            if (!empty($node['child'])) {
                $this->flattenTree($node['child'], $level + 1, $node['category_id'], $rows);
            }
        }
    }

    /**
     * 输出 CSV（UTF-8 BOM，Excel 友好）
     */
    private function outputCsv(string $filename, array $rows)
    {
        header('Content-Type: text/csv; charset=UTF-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        // UTF-8 BOM
        echo "\xEF\xBB\xBF";
        $fp = fopen('php://output', 'w');
        foreach ($rows as $row) {
            // 确保是纯字符串
            foreach ($row as &$cell) {
                if (is_null($cell)) $cell = '';
                if (is_array($cell) || is_object($cell)) $cell = json_encode($cell, JSON_UNESCAPED_UNICODE);
            }
            unset($cell);
            fputcsv($fp, $row);
        }
        fclose($fp);
        exit;
    }

}
